package com.kehongborui.fliggy.controller;

import com.kehongborui.fliggy.entity.User;
import com.kehongborui.fliggy.model.ResultModel;
import com.kehongborui.fliggy.service.UserService;
import com.kehongborui.fliggy.util.JedisUtil;
import com.kehongborui.fliggy.util.MailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import java.security.GeneralSecurityException;

/**
 * @author zhang peng yang ming
 * @CopyRight (C) http://www.csdn.com
 * @brief 用户注册
 * @email 122162005@qq.com
 * @date 2018-09-04
 */
@Controller
@RequestMapping("/reg")
public class RegController {
    @Autowired
    private UserService userService;
    @Autowired
    private JedisUtil jedisUtil;

    @GetMapping
    public String toRegPage() {
        return "reg/reg";
    }

    @ResponseBody
    @GetMapping("/tel/{tel}")
    public ResultModel telCheck(@PathVariable("tel") String tel) {
        User user = userService.findByTel(tel);
        // 用户存在，则返回对应的电话号码，不存在则返回空字符串
        return ResultModel.OK(user != null ? user.getTel() : "");
    }

//    @GetMapping(value = "/email/{email:[a-zA-Z0-9\\.\\@]+}", produces = "application/json;charset=UTF-8")
    @GetMapping(value = "/email")
    @ResponseBody
    public ResultModel emailCheck(String email) {
        User user = userService.findByEmail(email);
        // 用户存在，则返回对应的电话号码，不存在则返回空字符串
        return ResultModel.OK(user != null ? user.getEmail() : "");
    }

    @PostMapping
    public String reg(User user, ModelMap map) {
        //TODO 用户密码前端未加密
        map.addAttribute("user", user);
        return "reg/regInfo";
    }

    @PostMapping("/user_info")
    public String commitUserInfo(User user, ModelMap map) {
        boolean ret = userService.create(user);
        map.addAttribute("email", user.getEmail());
        return "reg/finish";
    }

    @GetMapping("/active")
    public String active(String code, ModelMap map) {
        String ret = jedisUtil.get(code);
        if (ret != null) {
            userService.enabledAccount(ret);
            map.addAttribute("tips", "激活成功，请到登录页面登录");
            return "reg/success";
        } else {
            map.addAttribute("tips", "已经过期");
            return "reg/success";
        }
    }
}
